package com.medicalsystem.service;

import com.medicalsystem.entity.Prescription;
import com.medicalsystem.repository.PrescriptionRepository;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

@Service
public class PrescriptionService {

    private final PrescriptionRepository prescriptionRepository;

    public PrescriptionService(PrescriptionRepository prescriptionRepository) {
        this.prescriptionRepository = prescriptionRepository;
    }

    // 获取所有处方信息
    public List<Prescription> getAllPrescriptions() {
        return prescriptionRepository.findAll();
    }

    // 根据ID获取处方信息
    public Prescription getPrescriptionById(Long id) {
        return prescriptionRepository.findById(id).orElse(null);
    }

    // 新增处方信息
    public Prescription savePrescription(Prescription prescription) {
        prescription.setCreateTime(new java.util.Date()); // 设置创建时间
        prescription.setUpdateTime(new java.util.Date()); // 设置更新时间
        return prescriptionRepository.save(prescription);
    }

    // 修改处方信息
    public Prescription updatePrescription(Long id, Prescription updatedPrescription) {
        Optional<Prescription> existingPrescription = prescriptionRepository.findById(id);
        if (existingPrescription.isPresent()) {
            Prescription prescription = existingPrescription.get();
            prescription.setDiagnosisId(updatedPrescription.getDiagnosisId());
            prescription.setPatientId(updatedPrescription.getPatientId());
            prescription.setPatientName(updatedPrescription.getPatientName());
            prescription.setDoctorId(updatedPrescription.getDoctorId());
            prescription.setDoctorName(updatedPrescription.getDoctorName());
            prescription.setPrescriptionDate(updatedPrescription.getPrescriptionDate());
            prescription.setPrescriptionType(updatedPrescription.getPrescriptionType());
            prescription.setMedicationAdvice(updatedPrescription.getMedicationAdvice());
            prescription.setTotalAmount(updatedPrescription.getTotalAmount());
            prescription.setStatus(updatedPrescription.getStatus());
            prescription.setRemark(updatedPrescription.getRemark());
            prescription.setUpdateTime(new java.util.Date()); // 设置更新时间
            return prescriptionRepository.save(prescription);
        }
        return null; // 如果未找到则返回 null
    }

    // 根据ID删除处方信息
    public void deletePrescription(Long id) {
        prescriptionRepository.deleteById(id);
    }
}
